package org.budo.warehouse.dao.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.budo.mybatis.dao.MybatisDao;
import org.budo.support.dao.page.Page;
import org.budo.support.dao.page.PageModel;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.warehouse.dao.api.IDataNodeDao;
import org.budo.warehouse.service.entity.DataNode;
import org.springframework.stereotype.Repository;

/**
 * @author limingwei
 */
@Repository
public class DataNodeDaoImpl implements IDataNodeDao {
    @Resource
    private MybatisDao mybatisDao;

    @Override
    public List<DataNode> listSourceDataNodes(Page page) {
        String sql = " SELECT * FROM t_datanode WHERE id IN ( SELECT source_datanode_id FROM t_pipeline WHERE deleted_at IS NULL OR deleted_at='' ) ";
        return mybatisDao.listBySql(DataNode.class, sql, null, page);
    }

    @Override
    public List<DataNode> listMysqlNodes(Page page) {
        String sql = " SELECT * FROM t_datanode WHERE url LIKE 'jdbc:mysql://%' ";
        return mybatisDao.listBySql(DataNode.class, sql, null, page);
    }

    @Override
    public DataNode findById(Integer id) {
        return mybatisDao.findById(DataNode.class, id);
    }

    @Override
    public PageModel<DataNode> list(Page page) {
        List<DataNode> list = mybatisDao.list(DataNode.class, page);
        for (DataNode dataNode : list) {
            String uname = dataNode.getUsername();
            String user = null;
            if (null == uname || uname.trim().isEmpty() || uname.trim().length() < 2) {
                user = uname;
            } else {
                Integer len = StringUtil.length(uname);
                user = uname.charAt(0) + StringUtil.dup("*", len - 2) + uname.charAt(len - 1);
            }

            String pwd = "*" + StringUtil.length(dataNode.getPassword()) + "*";

            dataNode.setUsername(user);
            dataNode.setPassword(pwd);
        }

        return new PageModel<DataNode>(list, page);
    }

    @Override
    public List<String> listNameByIds(List<Integer> ids) {
        String sql = " SELECT * FROM t_datanode WHERE id IN (#{ids}) ";
        Map<String, Object> parameter = MapUtil.stringObjectMap("ids", ids);
        return mybatisDao.listBySql(String.class, sql, parameter, Page.max());
    }
}